package com.necsv;

import java.util.ArrayList;
import java.util.List;

import com.necsv.Mylog.Mylog;

import Util.Constant;
import adapter.DBObject;
import adapter.DbAdapter;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class WebviewCustomActivity extends Activity{
	
	private WebView webview;
	List<DBObject>list;
	DbAdapter db;
	private static final String TAG = "LocalBrowser";
    private final Handler handler = new Handler();
    
    public String tmp = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Log.v(TAG, "On create");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview_custom);
		webview = (WebView) findViewById(R.id.webviewCustom);
		
		webview.getSettings().setJavaScriptEnabled(true);
		
//		webview.loadUrl(Constant.URL_VNEXPRESS);
		//get data from slite
		list = new ArrayList<DBObject>();
		db = new DbAdapter(this);
		db.open();
		Cursor mcCursor = db.getAllEntry();
		if(!mcCursor.moveToFirst())
		{
			db.insert(new DBObject("sonNEC",23));
			db.insert(new DBObject("VinhNEC",26));
		}
		//get data fill to list
		if(mcCursor.moveToFirst())
		{
			do
			{
				list.add(new DBObject(mcCursor.getString(1), mcCursor.getInt(2)));
			}while(mcCursor.moveToNext());
		}
		
		for (DBObject dbo : list) {
			Log.v("list", dbo.getName() + "-" + dbo.getAge());
		}
		
		final String fName = "son";
		final String lName ="Nguyen thanh";
		webview.addJavascriptInterface(new JavaScriptInterface(this), "Android");
		webview.addJavascriptInterface(new searchList(this), "Android");
		webview.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
//				String fuc = "javascript:(function() { "
//						+ "document.getElementsByTagName('body')[0].style.color = 'yellow'; " + "})()";
//				Log.v("tag", fuc);
//				 webview.loadUrl(fuc);
				 
				webview.loadUrl("javascript:document.getElementById('test').innerHTML = '"+fName+"';");
//				String table = "<table width = 100% border =1>" ;
				StringBuffer tableBuffer = new StringBuffer();
				tableBuffer.append("<table width = 100% border =1>");
				tableBuffer.append("<tr><td>Name</td><td>AGE</td></tr>");
				
				
				for(DBObject db : list)
				{
					tableBuffer.append("<tr>");
					tableBuffer.append("<td>");
					tableBuffer.append(db.getName());
					tableBuffer.append("</td>");
					tableBuffer.append("<td>");
					tableBuffer.append(db.getAge());
					tableBuffer.append("</td>");
					tableBuffer.append("</tr>");
				}
				tableBuffer.append("</table>");
				webview.loadUrl("javascript:document.getElementById('mydiv').innerHTML = '"+ tableBuffer.toString() +"';");
				
			}
		});

		webview.loadUrl(Constant.URL_HELLO);
		
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
	        webview.goBack();
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	private class AndroidBridge {
        public void callAndroid(final String arg) { //must be final
            handler.post(new Runnable() {
                public void run() {
                    Log.d(TAG, "callAndroid(" + arg + ")");
//                    textView.setText(arg);
                }
            }); 
        }
	}
	
	public class JavaScriptInterface {
	    Context mContext;

	    /** Instantiate the interface and set the context */
	    JavaScriptInterface(Context c) {
	        mContext = c;
	    }

	    /** Show a toast from the web page */
	    public void showToast(String toast) {
	        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
	    }
	}
	
	public class searchList{
		Context context;
		public searchList(Context context) {
			// TODO Auto-generated constructor stub
			this.context = context; 
		}
		
		public void search(String name1)
		{
//			String name1 = "Sonnt";
			
			//name = name.toString().trim();
			Log.e("TEST", "name " + name1);
			Cursor mcCursor = db.getEntryAt(name1);
			List<DBObject>listSearch = new ArrayList<DBObject>();
			if(mcCursor.moveToFirst())
			{
				Mylog.Toat(context, "not null");
				if(mcCursor.moveToFirst())
				{
					
					do
					{
						listSearch.add(new DBObject(mcCursor.getString(1), mcCursor.getInt(2)));
					}while(mcCursor.moveToNext());
				}
//				
				StringBuffer tableBuffer = new StringBuffer();
				tableBuffer.append("<table width = 100% border =1>");
				tableBuffer.append("<tr><td>Name</td><td>AGE</td></tr>");
				
				
				for(DBObject db : listSearch)
				{
					tableBuffer.append("<tr>");
					tableBuffer.append("<td>");
					tableBuffer.append(db.getName());
					tableBuffer.append("</td>");
					tableBuffer.append("<td>");
					tableBuffer.append(db.getAge());
					tableBuffer.append("</td>");
					tableBuffer.append("</tr>");
				}
				tableBuffer.append("</table>");
				
				tmp = tableBuffer.toString();
				handler.post(new Runnable() {
	                public void run() {
	                    webview.loadUrl("javascript:document.getElementById('mydiv').innerHTML = '"+ tmp +"';");
	                }
	            }); 
			}
		}
	}
	
	
}
